package com.elektronikforumet.camalert;

import java.io.File;
import java.io.FileFilter;

import android.content.Context;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.ListAdapter;

public class FolderAdapter extends BaseAdapter implements ListAdapter, OnClickListener {

	private Context mCtx = null;
	private File[] mFiles = null;
	private File mFolder = null;
	private String mFileType = "";
	private OnFileSelectedListener mOnFileSelectedListener = null;
	
	public FolderAdapter(Context ctx, File folder, String fileType) {
		mCtx = ctx;
		mFileType = fileType;
		
		try {
		setFolder(folder);
		} catch(Exception ex) {
			Log.d("CamAlert", "error error!", ex);
		}
	}
	
	public void setFolder(File folder) /* throws Exception */ {
		//if(!folder.isDirectory()) {
		//	throw new Exception("Must be folder!");
		//}
		
		mFolder = folder;
		
		mFiles = folder.listFiles( new FileFilter() {
			
			@Override
			public boolean accept(File pathname) {
				return pathname.isDirectory() || pathname.getName().endsWith(mFileType);
			}
		});
		
		notifyDataSetChanged();
	}
	
	@Override
	public int getCount() {
		return mFiles.length+1;
	}

	@Override
	public Object getItem(int position) {
		return mFiles[position];
	}

	@Override
	public long getItemId(int position) {
		// No problem with id 0
		return (long)position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		FileView fileView = null;
		
		if(convertView == null) {
			if(position == 0) {
				fileView = new FileView(mCtx, mFolder, true);
			} else {
				fileView = new FileView(mCtx, mFiles[position-1], false);
			}
			fileView.setOnClickListener(this);
		} else {
			fileView = (FileView)convertView;
			if(position == 0) {
				fileView.setFile(mFolder, true);
			} else {
				fileView.setFile(mFiles[position-1], false);
			}
		}
		
		return fileView;		
	}

	@Override
	public void onClick(View v) {
		FileView fv = (FileView)v;
		File f = fv.getFile();
		
		if(fv.getUp()) {
			setFolder(f.getParentFile());
		} else if(f.isDirectory()) {
			setFolder(f);
		} else {
			if(mOnFileSelectedListener != null) {
				mOnFileSelectedListener.onFileSelected(f);
			}
		}
		
		
	}
	
	public void setOnFileSelectedListener(OnFileSelectedListener listener) {
		mOnFileSelectedListener = listener;
	}
	
	public interface OnFileSelectedListener {
		void onFileSelected(File file);
	}

}
